//
//  DiyDrawView.m
//  BlueToothProject
//
//  Created by foshou on 2017/2/27.
//  Copyright © 2017年 yxw. All rights reserved.
//

#import "DiyDrawView.h"
#import "DiyHeader.h"
#import "UIImage+Convert.h"
#import "UIColor+RgbAndString.h"
#import "NSData+String.h"
@interface DiyDrawView ()

@property (nonatomic,strong) NSMutableArray *selectedPoints;
//@property (nonatomic,strong) NSMutableArray *eraserPoints;  //橡皮擦
@property (nonatomic,strong) NSMutableArray *controls;
@property (nonatomic,strong) NSMutableArray * rgbs;

@property (nonatomic, strong) NSMutableArray *colors; // 点阵颜色数组

@end

@implementation DiyDrawView
{
    UIView *backgroundView;
    BOOL isEraser;  //是否使用橡皮擦
    UIButton *selectedBtn;
//    UIView *lastPoint;
}

- (NSMutableArray *)colors{
    if (!_colors) {
        _colors = [NSMutableArray array];
    }return _colors;
}

-(NSMutableArray *)rgbs{
    if (!_rgbs) {
        _rgbs = [NSMutableArray new];
    }
    return _rgbs;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        //默认颜色
        self.LineColor = DefaultLineColor;
        
        //点阵图
        backgroundView = [[UIView alloc]initWithFrame:CGRectMake((frame.size.width-256*MultipleWideth-34)/2.0, 40, 256*MultipleWideth+34, 256*MultipleWideth+34)];
        backgroundView.backgroundColor = [UIColor clearColor];
        [self addSubview:backgroundView];
        
        backgroundView.backgroundColor = [UIColor colorWithRed:170.0/255.0 green:170.0/255.0 blue:170.0/255.0 alpha:1.0];
        self.controls = [[NSMutableArray alloc]init];
        CGFloat width = 16*MultipleWideth;
        for (int i=0; i<256; i++) {
          
                UIView *point = [[UIView alloc]initWithFrame:CGRectMake(2 + (i%16) * ( width + 2), 2 + (i / 16) * (width + 2), width, width)];
                point.backgroundColor = [UIColor blackColor];
                point.layer.cornerRadius = width/2.0;
                point.layer.masksToBounds = YES;
                point.tag = i;
                [backgroundView addSubview:point];
                [self.controls addObject:point];
                // 添加所有点的颜色
                [self.colors addObject:point.backgroundColor];
            
        }
        
        //操作按钮
        NSArray *buttonTitles = @[@"颜色",@"画笔",@"橡皮",@"生成",@"清除"];
        CGFloat buttonW = (frame.size.width-102)/5.0;
        for (int m=0; m<buttonTitles.count; m++) {
            UIButton *button  = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(17*(m+1)+buttonW*m, backgroundView.frame.size.height+110, buttonW, buttonW);
            button.tag = 100+m;
            [button setTitle:buttonTitles[m] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
            [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
            [button addTarget:self action:@selector(optionAction:) forControlEvents:UIControlEventTouchUpInside];
            
            button.layer.borderColor = [[UIColor grayColor] CGColor];
            button.layer.borderWidth = 0.8;
            button.layer.cornerRadius = 4.0;
            button.layer.masksToBounds = YES;
            if (m==1) {
                button.selected = YES;
                selectedBtn = button;
            }
            [self addSubview:button];
        }
        
        
    }
    return self;
}

-(void)optionAction:(UIButton *)sender
{
    selectedBtn.selected = NO;
    NSInteger temp = sender.tag-100;
    switch (temp) {
        case 0:
        {
            //选择颜色
            if (self.delegate && [self.delegate respondsToSelector:@selector(selectLineColor)]) {
                [self.delegate selectLineColor];
                [self.selectedPoints removeAllObjects];
            }
        }
            break;
        case 1:
        {
            //画笔
            sender.selected = YES;
            selectedBtn = sender;
            isEraser = NO;
        }
            break;
        case 2:
        {
            //橡皮
            isEraser = YES;
            sender.selected = YES;
            selectedBtn = sender;
        }
            break;
        case 3:
        {
            //生成
            if (self.delegate && [self.delegate respondsToSelector:@selector(saveImageAfterDone:)]) {
                
               
                
            UIImage *resultImg =    [self creatBitmap];
//
////                UIImage *resultImg = [self getImageFromView:backgroundView];
////                UIImage* nImage = [resultImg scaleToSize:resultImg size:CGSizeMake(16, 16)];
////                unsigned char *imageBytes = [UIImage pixelBRGABytesFromImage:resultImg];
////                UIImage *image = [UIImage imageFromBRGABytes:imageBytes imageSize:resultImg.size];
                [self.delegate saveImageAfterDone:resultImg]; //bytes:nil];
            }
        }
            break;
        case 4:
        default:
        {
            //清除
            [self.selectedPoints removeAllObjects];
            [self setNeedsDisplay];
            UIButton *button = (UIButton *)[self viewWithTag:101];
            button.selected = YES;
            selectedBtn = button;
            isEraser = NO;
//            lastPoint = nil;
        }
            break;
    }
}

#pragma mark - setter
-(void)setCancleEraser:(BOOL)cancleEraser
{
    _cancleEraser = cancleEraser;
    isEraser = !cancleEraser;
}

#pragma mark - lazyloading
-(NSMutableArray *)selectedPoints
{
    if (!_selectedPoints) {
        _selectedPoints = [[NSMutableArray alloc]init];
    }
    return _selectedPoints;
}

//-(NSMutableArray *)eraserPoints
//{
//    if (!_eraserPoints) {
//        _eraserPoints = [[NSMutableArray alloc]init];
//    }
//    return _eraserPoints;
//}

#pragma mark - touch
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    // 1. 获取当前触摸的点
    UITouch* touch = touches.anyObject;
    CGPoint loc = [touch locationInView:backgroundView];
    
    // 2. 判断当前触摸的点在哪个point范围之内
    for (int i = 0; i < self.controls.count; i++) {
        UIView* point = self.controls[i];
        if (CGRectContainsPoint(point.frame, loc)) {
            
            if (isEraser) {
                point.backgroundColor = [UIColor blackColor];
                if ([self.selectedPoints containsObject:point]) {
                    [self.selectedPoints removeObject:point];
                }
            }else {
                    if ([self.selectedPoints containsObject:point]) {
                        break;
                    }else {
                        [self.selectedPoints addObject:point];
                        break;
                    }
            }
        }
    }
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    [self touchesBegan:touches withEvent:event];
    
    [self setNeedsDisplay];
}

// 手指抬起事件
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    //重绘
//    lastPoint = nil;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    //如果数组不为空就执行
    NSLog(@"绘制");
    if (isEraser) {
        //        if (self.eraserPoints.count > 0) {
        //            for (NSInteger i=0; i < self.selectedPoints.count; i++) {
        //                UIView *view = [self.selectedPoints objectAtIndex:i];
        //                view.backgroundColor = [UIColor blackColor];
        //            }
        //        }
    }else {
        if (self.selectedPoints.count != 0) {
            for (NSInteger i=0; i < self.selectedPoints.count; i++) {
                UIView *view = [self.selectedPoints objectAtIndex:i];
                view.backgroundColor = self.LineColor;
                
                // 替换颜色
                NSInteger index = [self.controls indexOfObject:view];
                [self.colors replaceObjectAtIndex:index withObject:self.LineColor];
            }
        }else {
            for (NSInteger i=0; i < self.controls.count; i++) {
                UIView *view = [self.controls objectAtIndex:i];
                view.backgroundColor = [UIColor blackColor];
                
                // 替换颜色
                NSInteger index = [self.controls indexOfObject:view];
                [self.colors replaceObjectAtIndex:index withObject:view.backgroundColor];
            }
            
        }
    }
    
}

#pragma mark - UIView转UIImage

-(UIImage *)getImageFromView:(UIView *)theView
{
    //UIGraphicsBeginImageContext(theView.bounds.size);
    UIGraphicsBeginImageContextWithOptions(theView.bounds.size, YES, theView.layer.contentsScale);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, true, 0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
    
}

- (NSData *)getBmpData{
    NSMutableData *mData = [NSMutableData data];
    for (NSInteger i = 0; i < self.colors.count; i++) {
        UIColor *color = self.colors[i];
        NSData *data = [NSData dataForHexString:[UIColor toStrByUIColor:color]];
        [mData appendData:data];
    }
    
    return mData;
}

- (UIImage *)drawImage:(CGSize)size{
    
    UIGraphicsBeginImageContext(size);
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    for (NSInteger i = 0; i < self.colors.count; i++) {
        UIColor *color = self.colors[i];
        CGContextAddRect(ctx, CGRectMake(size.width/16 *(i%16), size.width/16 *(i/16), size.width/16, size.width/16));
        [color set];
        CGContextFillPath(ctx);
    }
    
    //4.获取生成的图片
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();

    
    UIGraphicsEndImageContext();
    
    return image;
}

//获取RGB值
- (UIImage *)getRGBComponents{
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    
    for (NSInteger i = 0; i < self.colors.count; i++) {
        UIColor *color = self.colors[i];
        CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
        unsigned char resultingPixel[4];
        CGContextRef context = CGBitmapContextCreate(&resultingPixel,
                                                     1,
                                                     1,
                                                     8,
                                                     4,
                                                     rgbColorSpace,
                                                     bitmapInfo);
        CGContextSetFillColorWithColor(context, [color CGColor]);
        CGContextFillRect(context, CGRectMake((i%16), (i/16), 1, 1));
        CGContextRelease(context);
        CGColorSpaceRelease(rgbColorSpace);
//        const CGFloat *components=CGColorGetComponents(color.CGColor);
//        for (int component = 0; component < 3; component++) {
//           resultingPixel[component] = components[component] ;
//        }

    }

    //4.获取生成的图片
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();

    return image;
}

- (UIImage *)creatBmp{
    
    CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
    CGFloat colors[self.colors.count * 4];
    for (NSInteger i = 0; i < self.colors.count; i++) {
        UIColor *color = self.colors[i];
        const CGFloat *components=CGColorGetComponents(color.CGColor);
        colors[i*4 + 0] = components[0] / 255.0;
        colors[i*4 + 1] = components[1] / 255.0;
        colors[i*4 + 2] = components[2] / 255.0;
        colors[i*4 + 3] = components[3] / 255.0;
    }
    

    
    
    
    CGGradientRef myGradient = CGGradientCreateWithColorComponents
    
    (rgb, colors, NULL, sizeof(colors)/(sizeof(colors[0])*4));
    
    // Allocate bitmap context
    
    CGContextRef bitmapContext = CGBitmapContextCreate(NULL, 16, 16, 8, 4 * 16, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst);

    
    // Draw Gradient Here
    
    /*
     
     创建好线性渐变后，我们将使用CGContextDrawLinearGradient过程在图形上下文中绘制，此过程需要五个参数：
     
     Graphics context 指定用于绘制线性渐变的图形上下文。
     
     Axial gradient 我们使用CGGradientCreateWithColorComponents函数创建的线性渐变对象的句柄
     
     start point 图形上下文中的一个CGPoint类型的点，表示渐变的起点。
     
     End Point表示渐变的终点。
     
     Gradient drawing options 当你的起点或者终点不在图形上下文的边缘内时，指定该如何处理。你可以使用你的开始或结束颜色来填充渐变以外的空间。此参数为以下值之一：KCGGradientDrawsAfterEndLocation扩展整个渐变到渐变的终点之后的所有点 KCGGradientDrawsBeforeStartLocation扩展整个渐变到渐变的起点之前的所有点。0不扩展该渐变。
     
     */
    
    CGContextDrawLinearGradient(bitmapContext, myGradient, CGPointMake(0.f, 0.0f),CGPointMake(0.f, 16),  kCGGradientDrawsBeforeStartLocation);
    
    // Create a CGImage from context
    
    CGImageRef cgImage = CGBitmapContextCreateImage(bitmapContext);
    
    // Create a UIImage from CGImage
    
    UIImage *uiImage = [UIImage imageWithCGImage:cgImage];
    
    // Release the CGImage
    
    CGImageRelease(cgImage);
    
    // Release the bitmap context
    
    CGContextRelease(bitmapContext);
    
    return uiImage;
}

- (CGContextRef)newBitmapRGBA8Context{
    CGContextRef context = NULL;
    CGColorSpaceRef colorSpace;
    uint32_t *bitmapData;
    
    size_t bitsPerPixel = 32;
    size_t bitsPerComponent = 8;
    size_t bytesPerPixel = bitsPerPixel / bitsPerComponent;
    
    size_t width = 16;
    size_t height = 16;
    
    size_t bytesPerRow = width * bytesPerPixel;
    size_t bufferLength = bytesPerRow * height;
    
    colorSpace = CGColorSpaceCreateDeviceRGB();
    
    if(!colorSpace) {
        NSLog(@"Error allocating color space RGB\n");
        return NULL;
    }
    
    // Allocate memory for image data
    bitmapData = (uint32_t *)malloc(bufferLength);
    
    if(!bitmapData) {
        NSLog(@"Error allocating memory for bitmap\n");
        CGColorSpaceRelease(colorSpace);
        return NULL;
    }
    
    //Create bitmap context
    
    
    context = CGBitmapContextCreate(bitmapData,
                                    width,
                                    height,
                                    bitsPerComponent,
                                    bytesPerRow,
                                    colorSpace,
                                    kCGImageAlphaPremultipliedLast);    // RGBA
    if(!context) {
        free(bitmapData);
        NSLog(@"Bitmap context not created");
    }
    
    CGColorSpaceRelease(colorSpace);
    
    return context;
}
//- (NSData *)convertUIImageToBitmapData
//{
//    
//    CGImageRef imageRef = self.CGImage;
//    
//    // Create a bitmap context to draw the uiimage into
//    CGContextRef context = [self newBitmapRGBA8Context];
//    if(!context) {
//        return NULL;
//    }
//    
//    size_t width = CGImageGetWidth(imageRef);
//    size_t height = CGImageGetHeight(imageRef);
//    
//    CGRect rect = CGRectMake(0, 0, width, height);
//    
//    // Draw image into the context to get the raw image data
//    CGContextDrawImage(context, rect, imageRef);
//    
//    // Get a pointer to the data
//    void *data = CGBitmapContextGetData(context);
//    
//    // Copy the data and release the memory (return memory allocated with new)
//    size_t bytesPerRow = CGBitmapContextGetBytesPerRow(context);
//    size_t bufferLength = bytesPerRow * height;
//    
//    NSData *datas = [NSData dataWithBytes:data length:bufferLength];
//    
//    
//    
//    CGContextRelease(context);
//    
//    return datas;
//}
- (UIImage *)convertBitmap{
    CGFloat width = 16;
    CGFloat height = 16;
    size_t bufferLength = width * height * 4;
    CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)[self getBmpData]);
    size_t bitsPerComponent = 8;
    size_t bitsPerPixel = 32;
    size_t bytesPerRow = 4 * width;
    
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    if(colorSpaceRef == NULL) {
        NSLog(@"Error allocating color space");
        CGDataProviderRelease(provider);
        return nil;
    }
    
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    
    CGImageRef iref = CGImageCreate(width,
                                    height,
                                    bitsPerComponent,
                                    bitsPerPixel,
                                    bytesPerRow,
                                    colorSpaceRef,
                                    bitmapInfo,
                                    provider,    // data provider
                                    NULL,        // decode
                                    YES,            // should interpolate
                                    renderingIntent);
    
    uint32_t* pixels = (uint32_t*)malloc(bufferLength);
    
    if(pixels == NULL) {
        NSLog(@"Error: Memory not allocated for bitmap");
        CGDataProviderRelease(provider);
        CGColorSpaceRelease(colorSpaceRef);
        CGImageRelease(iref);
        return nil;
    }
    CGContextRef context = CGBitmapContextCreate(pixels,
                                                 width,
                                                 height,
                                                 bitsPerComponent,
                                                 bytesPerRow,
                                                 colorSpaceRef,
                                                 bitmapInfo);
    
    if(context == NULL) {
        NSLog(@"Error context not created");
        free(pixels);
    }
    
    UIImage *image = nil;
    if(context) {
        CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), iref);
        CGImageRef imageRef = CGBitmapContextCreateImage(context);
        // Support both iPad 3.2 and iPhone 4 Retina displays with the correct scale
        if([UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)]) {
            float scale = [[UIScreen mainScreen] scale];
            image = [UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
        } else {
            image = [UIImage imageWithCGImage:imageRef];
        }
        CGImageRelease(imageRef);
        CGContextRelease(context);
    }
    CGColorSpaceRelease(colorSpaceRef);
    CGImageRelease(iref);
    CGDataProviderRelease(provider);
    if(pixels) {
        free(pixels);
    }
    return image;
}

- (UIImage *)creatBitmap{
    
    size_t w = 16;
    size_t h = 16;
    long size = w * h;

    unsigned char* rgba = (unsigned char*)malloc(size *4);
    for(int i = 0; i < size; i++) {
        UIView *view = (UIView *)self.controls[i];
        UIColor *color = view.backgroundColor;
        const CGFloat *components=CGColorGetComponents(color.CGColor);
        rgba[4*i]   = strtoul([[UIColor ToHex:components[0] * 255.0f] UTF8String],0,16);
        rgba[4*i+1] = strtoul([[UIColor ToHex:components[2] * 255.0f] UTF8String],0,16);
        rgba[4*i+2] = strtoul([[UIColor ToHex:components[3] * 255.0f] UTF8String],0,16);
        rgba[4*i+3] = strtoul([[UIColor ToHex:components[1] * 255.0f] UTF8String],0,16);

        
    }
    
    NSLog(@"%@",[NSData dataWithBytes:rgba length:size*4]);
    
    // 构造图像
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef bitmapContext = CGBitmapContextCreate(rgba,w,h,8,4*w,colorSpace,kCGImageAlphaPremultipliedLast);
    if (!bitmapContext) {
        NSLog(@"位图上下文为空！");
        return nil;
    }
    CGImageRef cgRef = CGBitmapContextCreateImage(bitmapContext);
    UIImage* image = [UIImage imageWithCGImage: cgRef];
    
    if (rgba != NULL) {
        free(rgba);// 释放原始数据
    }
    CGColorSpaceRelease( colorSpace );
    CGImageRelease(cgRef);
    CGContextRelease(bitmapContext);
    return image;
}


//将字符转换为对应的asci值
- (Byte)toByte:(unichar)ch;
{
    if (ch>='a' && ch<='f')
    {
        return ch-'a'+10;
    }
    else if (ch>='A' && ch<='F')
    {
        return ch-'A'+10;
    }
    else if (ch>='0' && ch<='9')
    {
        return ch-'0';
    }
    else
    {
        return 0;
    }
}



@end
